﻿using LY.Manage.Model;
using LY.Manage.Model.EnumType;
using LY.Manage.WebApp.App_Start;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace LY.Manage.WebApp.Controllers
{
    public class RoleInfoController : BaseController
    {
        //
        // GET: /RoleInfo/

        IBLL.IRoleInfoService RoleInfoService { get; set; }
        IBLL.Isys_menuService sys_menuService { get; set; }

        IBLL.Isys_roleMenuMapService sys_roleMenuMapService { get; set; }

        public int idzhi;
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowRoleMenu()
        {

            int roleId = Convert.ToInt32(Request["roleId"]);
            // GetUserTreeJson();
            RoleInfo roleInfo = RoleInfoService.LoadEntities(u => u.ID == roleId).FirstOrDefault();

            ViewBag.RoleInfo = roleInfo;

            return View();

        }
        /// <summary>
        /// 树形菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]

        public ActionResult GetUserTreeJson()
        {

            int userId = int.Parse(Request["roleIdzhi"]);
            bool checkzhi = false;
            string pcode = "0";
            List<EasyTreeData> treeList = new List<EasyTreeData>();
            if (pcode == "0")
            {
                //获取所有的父导航
                var menuList = sys_menuService.LoadEntities(u => true);
                var list = (from p in menuList
                            where p.ParentCode == pcode
                            orderby p.ParentCode
                            select p).ToList();
                foreach (var info in list)
                {
                    var child = (from p in menuList
                                 where p.ParentCode == info.MenuCode
                                 orderby p.ParentCode
                                 select p).ToList();

                    //  判断一下 当前的菜单是否已经选中
                    var rolemenu = sys_roleMenuMapService.LoadEntities(u => u.RoleId == userId && u.MenuCode == info.MenuCode);

                    if (rolemenu.Count() > 0)
                    {
                        checkzhi = true;
                    }
                    else
                    {
                        checkzhi = false;
                    }
                    if (child.Count == 0)
                    {
                        treeList.Add(new EasyTreeData(info.MenuCode, info.MenuName, "icon-user", checkzhi));
                    }
                    else
                    {
                        int ids = 0;
                        treeList.Add(new EasyTreeData(ids, info.MenuCode, info.MenuName, "icon-user", checkzhi, "open", GetUserTreeJson2(info.MenuCode)));


                    }
                }
            }
            string json = ToJson(treeList);
            json = json.Replace("checkeds", "checked");
            return Content(json);
        }
        private List<EasyTreeData> GetUserTreeJson2(string PID)
        {
            int userId = int.Parse(Request["roleIdzhi"]);

            bool checkzhi = false;
            List<EasyTreeData> treeList = new List<EasyTreeData>();
            var menuList = sys_menuService.LoadEntities(u => u.ParentCode == PID);

            var list = (from p in menuList
                        where p.ParentCode == PID
                        orderby p.ParentCode
                        select p).ToList();
            foreach (var info in list)
            {
                var child = (from p in menuList
                             where p.ParentCode == info.MenuCode
                             orderby p.ParentCode
                             select p).ToList(); ;

                //  判断一下 当前的菜单是否已经选中
                var rolemenu = sys_roleMenuMapService.LoadEntities(u => u.RoleId == userId && u.MenuCode == info.MenuCode);

                if (rolemenu.Count() > 0)
                {
                    checkzhi = true;
                }
                else
                {
                    checkzhi = false;
                }


                if (child.Count == 0)
                {
                    treeList.Add(new EasyTreeData(info.MenuCode, info.MenuName, "icon-user", checkzhi));
                }
                else
                {
                    int ids = 0;
                    treeList.Add(new EasyTreeData(ids, info.MenuCode, info.MenuName, "icon-user", checkzhi, "open", GetUserTreeJson2(info.MenuCode)));
                }
            }
            return treeList;

        }

        protected string ToJson(object obj)
        {
            string jsonData = (new JavaScriptSerializer()).Serialize(obj);
            return jsonData;
        }
        #region 获取角色列表
        public ActionResult GetRoleInfoList()
        {
            int pageIndex = Request["page"] != null ? int.Parse(Request["page"]) : 1;
            int pageSize = Request["rows"] != null ? int.Parse(Request["rows"]) : 5;
            int totalCount = 0;
            short delFlag = (short)DeleteEnumType.Normarl;
            var roleInfoList = RoleInfoService.LoadPageEntities<int>
                (pageIndex, pageSize,
                out totalCount,
                u => u.DelFlag == delFlag,
                u => u.ID,
                true
                );
            var temp = from r in roleInfoList
                       select new
                       {
                           ID = r.ID,
                           RoleName = r.RoleName,
                           Sort = r.Sort,
                           SubTime = r.SubTime,
                           Remark = r.Remark
                       };

            return Json(new
            {
                rows = temp,
                total = totalCount
            }, JsonRequestBehavior.AllowGet);

        }
        #endregion
        #region 展示添加表单 ShowAddInfo

        public ActionResult ShowAddInfo(RoleInfo roleInfo)
        {
            return View();

        }
        #endregion
        #region 完成角色信息的添加 AddRoleInfo
        public ActionResult AddRoleInfo(RoleInfo roleInfo)
        {
            roleInfo.ModifiedOn = DateTime.Now;
            roleInfo.SubTime = DateTime.Now;
            roleInfo.DelFlag = (short)DeleteEnumType.Normarl;
            RoleInfoService.AddEntity(roleInfo);
            return Content("ok");
        }

        public ActionResult AddRoleMenu(sys_roleMenuMap roleMenuMap)
        {

            //先删除当前用户的权限
            int userId = int.Parse(Request["roleId"]);
            List<sys_roleMenuMap> menulist = sys_roleMenuMapService.LoadEntities(u => u.RoleId == userId).ToList();
            foreach (var menu in menulist)
            {

                sys_roleMenuMapService.DeleteEntity(menu);
            }
            //将list集合存储的要删除的记录的编号传递到业务层

            //添加 新增用户
            string sMenuList = Request.Form["menulist"];
            string[] pMenu = sMenuList.Split(',');


            ArrayList al = new ArrayList();
            foreach (string menucode in pMenu)
            {
                if (menucode.Trim() == "")
                    continue;
                if (menucode.Length >= 4)
                {
                    //获取编码前2个作为父节点
                    string pCode = menucode.Substring(0, 2);
                    if (!al.Contains(pCode))
                        al.Add(pCode);
                }


                roleMenuMap.RoleId = userId;
                roleMenuMap.MenuCode = menucode;
                sys_roleMenuMapService.AddEntity(roleMenuMap);
            }
            for (int i = 0; i < al.Count; i++)
            {
                roleMenuMap.RoleId = userId;
                roleMenuMap.MenuCode = al[i].ToString();
                sys_roleMenuMapService.AddEntity(roleMenuMap);
            }


            return Content("ok");
        }

        //public ActionResult AddRoleMenu(sys_roleMenuMap roleMenuMap)
        //{




        // //先删除当前用户的权限
        //int userId = int.Parse(Request["roleId"]);
        //List<sys_roleMenuMap> menulist = sys_roleMenuMapService.LoadEntities(u => u.RoleId ==userId).ToList();
        //foreach (var menu in menulist)
        // {

        //     sys_roleMenuMapService.DeleteEntity(menu);
        //}

        ////将list集合存储的要删除的记录的编号传递到业务层

        ////添加 新增用户

        //string sMenuList = Request.Form["menulist"];
        //if (sMenuList != "")
        //{
        //    string[] pMenu = sMenuList.Split(',');


        //    ArrayList al = new ArrayList();
        //    foreach (string menucode in pMenu)
        //    {
        //        if (menucode.Trim() == "")
        //            continue;
        //        if (menucode.Length >= 4)
        //        {
        //            //获取编码前2个作为父节点
        //            string pCode = menucode.Substring(0, 2);
        //            if (!al.Contains(pCode))
        //                al.Add(pCode);
        //        }


        //        roleMenuMap.RoleId = userId;
        //        roleMenuMap.MenuCode = menucode;
        //        sys_roleMenuMapService.AddEntity(roleMenuMap);
        //    }
        //    for (int i = 0; i < al.Count; i++)
        //    {
        //        roleMenuMap.RoleId = userId;
        //        roleMenuMap.MenuCode = al[i].ToString();
        //        sys_roleMenuMapService.AddEntity(roleMenuMap);
        //    }



        //}
        // return Content("ok");
        // }
        #endregion
        #region 展示要修改的数据

        public ActionResult ShowEditInfo()
        {

            int id = int.Parse(Request["id"]);
            RoleInfo model = RoleInfoService.LoadEntities(u => u.ID == id).FirstOrDefault();

            return View(model);


        }
        #region 完成用户数据的更新
        public ActionResult EditUserInfo(RoleInfo entity)
        {
            //1.根据主键ID查询数据
            RoleInfo roleInfo = RoleInfoService.LoadEntities(u => u.ID == entity.ID).FirstOrDefault();
            if (entity == null)
            {
                return Content("no");
            }

            #region 2.设置要修改的数据

            roleInfo.RoleName = entity.RoleName;
            roleInfo.Remark = entity.Remark;
            roleInfo.Sort = entity.Sort;
            // userinfo.UPwd = entity.UPwd;

            #endregion


            //3.更新数据，并返回
            if (RoleInfoService.UpdateEntity(roleInfo))
            {
                return Content("ok");
            }
            else
            {
                return Content("no");
            }


        }
        #endregion
        #endregion
        #region 删除数据方法 DeleteInfo
        public ActionResult DeleteInfo()
        {
            string strId = Request["strId"];
            int id = Convert.ToInt32(strId);
            RoleInfo entity = RoleInfoService.LoadEntities(u => u.ID == id).FirstOrDefault();

            if (entity == null)
            {
                return Content("no");
            }
            //将list集合存储的要删除的记录的编号传递到业务层
            if (RoleInfoService.DeleteEntity(entity))
            {
                return Content("ok");
            }
            else
            {
                return Content("no");
            }

        }
        #endregion
    }
}
